package com.feihao.zhou.WorkTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

/**
 * 4.  定义一个学生类Student，包含三个属性姓名、年龄、性别，创建三个学生对象存入ArrayList集合中。
 A：遍历集合遍历输出。
 B：求出年龄最大的学生，然后将该对象的姓名变为：小猪佩奇。
 */
public class Demo3 {
    public static void main(String[] args) {
        //创建学生对象并存入集合：
        Student student1 = new Student("张三",18,"男");
        Student student2 = new Student("李四",122,"女");
        Student student5 = new Student("上述",77,"女");
        Student student6 = new Student("酷酷酷",4,"女");
        Student student3 = new Student("王五",17,"男");

        ArrayList<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student5);
        list.add(student6);
        list.add(student2);
        list.add(student3);

        //遍历集合并输出：
        for (Student student : list) {
            System.out.println(student);
        }

        System.out.println("=============================");

        //求出年龄最大的学生，然后将该对象的姓名变为：小猪佩奇。
        /*for (int i = 0; i < list.size(); i++) {
            Student s = list.get(i);

        }*/


        /*Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge() - o1.getAge();
            }
        });
        Student student = list.get(0);
        student.setName("小猪佩奇");*/

        //假设一个年龄最大的学生是list.get(0);
        Student max = list.get(0);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getAge()>max.getAge()){//如果遍历集合中有学员年龄比设置的学生年龄大，这交换。
                max = list.get(i);
            }
        }
        max.setName("小猪拍拍");

        Iterator<Student> iterator = list.iterator();
        while (iterator.hasNext()){
            Student s = iterator.next();
            System.out.println(s);
        }
    }
}
